package model

import (
	"ginTea/structs"
	"ginTea/utils/errmsg"
	"ginTea/utils/helpers"
	"time"

	"github.com/jinzhu/gorm"
)

type Notice struct {
	ID        uint      `gorm:"primary_key" json:"id"`
	CreatedAt time.Time `json:"created_at" gorm:"column:created_at;autoCreateTime"`
	UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at;autoCreateTime"`
	UserId    int       `gorm:"not null" json:"user_id"`
	UserInfo  User      `gorm:"foreignkey:UserId" json:"user_info"`
	Title     string    `gorm:"not null" json:"title"`
	Content   string    `gorm:"not null" json:"content"`
	ImageUrl  string    `gorm:" not null" json:"image_url"`
	IsShow    bool      `gorm:"default:true; not null" json:"is_show"`
}

// 新增公告
func CreateNotice(data *Notice) int {
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	} else {
		return errmsg.SUCCESS
	}
}

// 删除公告
func DeleteNotice(id int) int {
	var data Notice
	db.Select("id").Where("id=?", id).First(&data)
	if data.ID > 0 {
		err := db.Unscoped().Where("id = ?", id).Delete(&data).Error
		if err != nil {
			return errmsg.ERROR
		}
		return errmsg.SUCCESS
	}
	return errmsg.ERROR
}

/*
获取所有公告
pageNum 当前页号
pageSize当前页大小
*/
func GetNoticeList(page int, pageSize int) structs.JSONResponse {
	// var NoticeList []Notice
	var test []Notice
	var total int
	var list []interface{}
	tx := db.Model(&test).Where("ID >0")
	tx = tx.Preload("UserInfo")
	tx.Count(&total)
	err := tx.Order("id desc").
		Limit(pageSize).
		Offset((page - 1) * pageSize).
		Find(&test).
		RecordNotFound()
	if err {
		return helpers.Error("")
	}
	for _, v := range test {
		list = append(list, v)
	}
	pageData := structs.NewPageData(list, pageSize, page, total)
	response := helpers.Success(pageData)
	return response
}

// 获取公告详情
func GetNoticeInfo(id int) ([]Notice, int) {
	var NoticeInfo []Notice
	err := db.Preload("UserInfo").Where("id=?", id).First(&NoticeInfo).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR
	}
	return NoticeInfo, errmsg.SUCCESS
}

// 编辑公告
func UpdateNotice(id int, data *Notice) int {
	var Notice Notice
	var maps = make(map[string]interface{})
	maps["title"] = data.Title
	maps["image_url"] = data.ImageUrl
	maps["content"] = data.Content
	maps["is_show"] = data.IsShow
	err := db.Model(&Notice).Where("id = ?", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
